package talk_server;

import java.io.IOException;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;

import side_server.Server_Clear;
import side_server.Server_Files;
import side_server.Server_Join;
import side_server.Server_Launch;
import side_server.Server_Leave;
import side_server.Server_Peers;
import side_server.Server_Share;

public class SocketManager implements Runnable{
	@SuppressWarnings("unused")
	private Socket socket;
	private Talker talker;
	public SocketManager(Socket socket)
	{
		this.socket=socket;
		this.talker = new Talker(socket);
	}
	
	public String read()
	{
		String msg = null;
		try {
			msg =  talker.read();
		} catch (IOException e) {
			System.out.println("SOCKET MANAGER: ERRORE I/O");
		}
		return msg;
	}
	
	public void write(String msg)
	{
		try {
			talker.write(msg);
		} catch (IOException e) {
			System.out.println("SOCKET MANAGER: ERRORE I/O");
		}
	}

	@Override
	public void run() {
		String msg = read();
		try {
			System.out.println("*****************************");
			System.out.println("PARSING MESSAGE: " + msg);
			System.out.println("*****************************");
			ParseMessage(msg);
		} catch (IOException e) {
			System.out.println("SOCKET MANAGER: ERRORE I/O");
		}
	}
	
	private void ParseMessage(String msg) throws IOException
	{
		msg = msg.toUpperCase();
		if(msg.equals("LISTPEERS"))
			new Server_Peers(talker);
		else
		if(msg.equals("LISTFILES"))
			new Server_Files(talker);
		else
		if(msg.equals("LEAVE"))
			new Server_Leave(talker);
		else
		if(msg.equals("WAIT"))
			System.out.println("WAITING...");
		else
		if(msg.equals("JOIN"))
			new Server_Join(talker);
		else
		if(msg.equals("CLEARPEERS"))
			new Server_Clear(talker);
		else
		if(msg.equals("SHARE"))
			Server_Share.receive(talker);
		else
		if(msg.equals("SEND"))
			Server_Share.send(talker);
		else
		if(msg.equals("HELLO"))
			talker.write("HI");
		else
		if(msg.equals("GETPEERS"))
			getPeers(talker);
		else
		if(msg.equals("NEXT"))
			getPeers(talker);
		else
			System.out.println(msg);
	}
	
	private void getPeers(Talker talker) throws IOException
	{
		HashSet<String> peers = Server_Launch.getInstance().getKeys();
		Iterator<String> it   = peers.iterator();
		while(it.hasNext())
		{
			String peer = it.next();
			System.out.println("REQUEST FOR PEER " + peer);
			talker.write(peer);
			talker.read();
		}
		talker.write("STOP");
	}
	
}
